package com.freewater.javabase.demo.network.cookie;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class RequestCookieDemo {
    public static void main(String[] args) throws IOException, URISyntaxException {
        URI uri = new URI("https://www.baidu.com/s?wd=人工智能");
        URL url = uri.toURL();
        final URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Cookie", "username=freewater;gender=male");
        urlConnection.addRequestProperty("Cookie", "address=chengdu;tel=13888888888");
        System.out.println(urlConnection.getRequestProperties());
        //
        try (final InputStream inputStream = url.openStream();
             final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] bytes = new byte[1024];
            int count;
            while ((count = inputStream.read(bytes)) != -1) {
                bos.write(bytes, 0, count);
            }
            bos.flush();
            System.out.println(bos.toString(Charset.forName("utf-8")).substring(0, 100));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
